package kr.hkit.wordnote.main;

import java.util.ArrayList;

import kr.hkit.wordnote.R;
import kr.hkit.wordnote.db.WordDBHelper;
import kr.hkit.wordnote.db.WordDTO;
import kr.hkit.wordnote.exception.DBException;
import kr.hkit.wordnote.fragment.WordFindFragment;
import kr.hkit.wordnote.fragment.WordInputFragment;
import kr.hkit.wordnote.fragment.WordListFragment;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

public class ActionTab extends Activity implements WordInputFragment.OnWordChangedListener, 
												WordListFragment.OnEditButtonClickedListener{
	final static String TAG = "ActionTab";
	int checkNum = 0;
	ActionBar actionbar;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mainactiontab);
		
		actionbar = getActionBar();
		actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		
		
		
		//db로부터 받은 데이터를 저장할 arraylist를 준비한다.
		ArrayList<String> engList = new ArrayList<>();
		ArrayList<String> korList = new ArrayList<>();
		
		//getWord 메서드를 호출하여 전달받은 engword와 korword를 engList와 korList에 담는다. 
		ArrayList<WordDTO> arList = getWord();
		for(int i=0; i<arList.size(); i++){
			WordDTO dto = arList.get(i);
			engList.add(dto.getEng());
			korList.add(dto.getKor());
		}
			
		//캡션으로 사용할 텍스트를 arrayList에 저장한다. 
		ArrayList<String> arrCap = new ArrayList<>();
		arrCap.add("단어목록");
		arrCap.add("단어추가");
		arrCap.add("단어검색");
		arrCap.add("깜빡이");
		
		
		for(int i=0; i<4; i++){
			//각각의 탭에 캡션을 지정한다.
			ActionBar.Tab tab = actionbar.newTab();
			String cap = arrCap.get(i);
			tab.setText(cap);
			//if문으로 각각의 탭에 따라 생성할 프레그먼트 객체를 분리한다.
			Fragment frag = null;
			if(i == 0){
				frag = WordListFragment.newInstance(engList, korList);
			}else if(i == 1){
				frag = WordInputFragment.newInstance(engList);
			}else if(i == 2){
				frag = WordFindFragment.newInstance();
			}
			tab.setTabListener(new TabListener(frag));
			actionbar.addTab(tab);
		}
		
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("seltab", getActionBar().getSelectedNavigationIndex());
	}



	private class TabListener implements ActionBar.TabListener{
		private Fragment mFragment;
		
		public TabListener(Fragment fragment){
			Log.d(TAG, "TabListener");
			mFragment = fragment;
		}
		
		@Override
		public void onTabSelected(Tab tab, FragmentTransaction ft) {
			Log.d(TAG, "onTabSelected");
			//DB에 단어가 추가, 갱신, 삭제 되었을 때 korword와 engword를 다시 받아온다.
			if(checkNum == 1){
				ArrayList<WordDTO> arList = getWord();
				ArrayList<String> engList = new ArrayList<>();
				ArrayList<String> korList = new ArrayList<>();
				
				for(int i=0; i<arList.size(); i++){
					WordDTO dto = arList.get(i);
					engList.add(dto.getEng());
					korList.add(dto.getKor());
				}
				
				if(tab.getPosition() == 0){
					mFragment = WordListFragment.newInstance(engList, korList);
				}else if(tab.getPosition() == 1){
					mFragment = WordInputFragment.newInstance(engList);
				}			
				checkNum = 0;
			}
		
			ft.add(R.id.tabparent, mFragment);
		}

		@Override
		public void onTabUnselected(Tab tab, FragmentTransaction ft) {
			Log.d(TAG, "onTabUnselected");
			
			//'단어검색' 탭에서 키보드 띄운 후 또 다른 탭을 선택했을 때, 생성되어 있던 키보드를 사라지게 한다. 
			if(tab.getPosition() == 1){
				EditText engedit = (EditText)findViewById(R.id.engedit);
				InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(engedit.getWindowToken(), 0);
			}
			ft.remove(mFragment);
			
		}

		@Override
		public void onTabReselected(Tab tab, FragmentTransaction ft) {
			
		}
	}

	@Override
	public void onWordChanged(int num) {
		Log.d(TAG, "onWordAddListener");
		checkNum = num;
	}
	
	@Override
	public void onButtonClicked(String eng, String kor) {
		Log.d(TAG, "onButtonClicked");		
		actionbar.setSelectedNavigationItem(1);
		/*EditText engEdit = (EditText)ActionTab.this.findViewById(R.id.engedit);
		EditText korEdit = (EditText)ActionTab.this.findViewById(R.id.koredit);
		engEdit.setText(eng);
		korEdit.setText(kor);*/
	}
	
	public ArrayList<WordDTO> getWord(){
		//DB로부터 word 데이터를 받아오는 selectWord메소드를 실행시켜, 값들을 arrayList에 저장한다. 
		WordDBHelper helper = null;
		ArrayList<WordDTO> arList = null;
		try {
			helper = new WordDBHelper(this);
			arList = helper.selectWord();
		} catch (DBException e) {
			Toast.makeText(this, e.getMessage(), 0).show();
		} finally {
			helper.close();
		}
		return arList;
	}
}
